<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="userObj.uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="userObj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="userObj.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addOrEditList">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delUser(item.id)">删除</button>
            <button @click="editUser(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          uname: 'ikun',
          age: 18,
          gender: '男',
        },
        {
          id: 2,
          uname: 'crapper',
          age: 25,
          gender: '男',
        },
      ],

      userObj: {
        id: '',
        uname: '',
        age: '',
        gender: '',
      },

      //控制是添加还是修改操作
      flag: true,
    }
  },

  methods: {
    addOrEditList() {
      //flag为true 为添加操作
      if (this.userObj.uname && this.userObj.age && this.userObj.gender) {
        if (this.flag) {
          const obj = { ...this.userObj }
          this.list = [...this.list, obj]

          this.userObj.uname = ''
          this.userObj.gender = ''
          this.userObj.age = ''
        } else {
          this.list.forEach((item) => {
            if (item.id === this.userObj.id) {
              item.uname = this.userObj.uname
              item.age = this.userObj.age
              item.gender = this.userObj.gender
            }

            this.userObj.uname = ''
            this.userObj.gender = ''
            this.userObj.age = ''
          })

          this.flag = true
        }
      } else {
        alert('内容不能空')
      }
    },

    //编辑功能
    editUser(id) {
      const obj = this.list.find((item) => item.id === id)

      this.userObj = { ...obj }

      this.flag = false
    },

    //删除功能
    delUser(id) {
      if (!this.flag) return alert('现在不能做删除操作')
      this.list = this.list.filter((item) => item.id !== id)
    },
  },
}
</script>
